<!DOCTYPE HTML>
<html>
	<div id="app">
		<button @click="startBlue">{{msg}}</button>
		<div>
			<ul>
				<li>未配对列表(点击开始配对)</li>
				<button type="button" @click="Bluepairing(index)" v-for="(item,index) in Unpairedlist">
					{{item.bleName}}
				</button>
			</ul>
			读取标签：{{read_lableId}} <br />
			固件版本：{{firmwareId}} <br />
			工作温度：{{temperature}} <br />
			选中的标签： {{select_lableId}}
			<ul>
				<li>已配对列表(点击连接)</li>
				<button type="button" @click="ConnectDevice(index)" v-for="(item,index) in Pairedlist">
					{{item.bleName}}
				</button>
			</ul>
			<button id="scanButton" @click="open()">开始盘点</button>
			<button @click="reset()">读写器复位</button>
			<button id="read_lable" @click="open_read_lable()">测试读取标签</button>
			<button id="read_firmware" @click="open_read_firmware()">获取固件版本</button>
			<button id="read_temperature" @click="open_read_temperature()">获取温度</button>
			<button id="select_lable" @click="open_set_lable(item)">写入标签</button>

			<ul>
				<li>
					扫描到的标签（点击选取)
					<button type="button" @click="open_select_lable(obj.arr)" v-for="(obj,index) in dataList">
						{{obj.hex}}
					</button>
				</li>

			</ul>
		</div>
	</div>
</html>

<script src="js/vue.js"></script>
<script src="js/mui.js"></script>
<!-- <script src="js/CMD.js"></script> -->
<script>
	mui.init();
	let connectDevice = null;
	let bleSocket = null;
	let timer = null;
	let connectId = null;
	let firstSelect = -1;

	// 将十六进制数组传为字符串
	function hex2String(hexArr) {
		let len = hexArr.length;
		let result = "";
		for (let i = 0; i < len; i++) {
			result += String(hexArr[i]);
		}
		return result;
	}

	// 十六进制数组转字符串
	function hexArr2String(hexArr) {
		var val = "";
		for (var i = 0; i < hexArr.length; i++) {
			val += String.fromCharCode(parseInt(hexArr[i], 16));
		}
		return val;
	}

	//十六进制字符串转字节数组
	function HexString2Bytes(str) {
		var pos = 0;
		var len = str.length;
		if (len % 2 != 0) {
			return 0;
		}
		len /= 2;
		var arrBytes = new Array();
		for (var i = 0; i < len; i++) {
			var s = str.substr(pos, 2);
			var v = parseInt(s, 16);
			arrBytes.push(v);
			pos += 2;
		}
		return arrBytes;
	}



	// 十六进制数组转字节数组
	function HexArr2Bytes(hexArr) {
		let bytes = new Array();
		let len = hexArr.length;
		for (var i = 0; i < len; i++) {
			bytes.push(Number(HexString2Bytes(hexArr[i])))
		}
		return bytes;
	}

	//字节数组转十六进制数组，对负值填坑
	// function Bytes2HexArr(arrBytes) {
	// 	let HexArr = new Array();
	// 	for (var i = 0; i < arrBytes.length; i++) {
	// 		var tmp;
	// 		var num = arrBytes[i];
	// 		if (num < 0) {
	// 			//此处填坑，当byte因为符合位导致数值为负时候，需要对数据进行处理
	// 			tmp = (255 + num + 1).toString(16);
	// 		} else {
	// 			tmp = num.toString(16);
	// 		}
	// 		tmp = num.toString(16);
	// 		if (tmp.length == 1) {
	// 			tmp = "0" + tmp;
	// 		}
	// 		HexArr.push(tmp)
	// 	}
	// 	return HexArr;
	// }

	//字符串转十六进制数组
	function String2HexArr(str) {
		let value = new Array();
		for (var i = 0; i < str.length; i++) {
			if (value == "") {
				value.push(str.charCodeAt(i).toString(16));
			} else {
				value.push(str.charCodeAt(i).toString(16));
			}
		}
		return value;
	}

	// 字节数组转十六进制字符串
	function bytesToHexArr(inarray) {
		var i, j, x;
		var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
			"B", "C", "D", "E", "F"
		];
		var inArr = new Array();
		for (j = 0; j < inarray.length; ++j) {
			var out = "";
			x = inarray[j] & 0xff;
			i = (x >> 4) & 0x0f;
			out += hex[i];
			i = x & 0x0f;
			out += hex[i];
			inArr.push(out)
		}
		return inArr;
	}

	// 将获取的十六进制数组转为数据字符串
	function hex2DataString(inArr) {
		// 获取数据长度
		let dataLen = inArr[0];
		let data = "";
		for (let i = 1; i <= dataLen; i++) {
			data += inArr[i];
		}
		// 数据中含有A统一替换为S
		data = data.replace('A', 'S')
		return data;
	}

	/*
	 * 获取某个元素下标
	 * arr: 传入的数组
	 * obj: 需要获取下标的元素
	 * */
	function getArrayIndex(arr, obj) {
		var i = arr.length;
		var indexArr = [];
		while (i--) {
			if (arr[i] === obj) {
				indexArr.unshift(i);
			}
		}
		return indexArr;
	}

	/*
	 * string2BytesArr
	 * @param {Object} str
	 */
	function string2Bytes(str) {
		let ch, st, re = [];
		for (var i = 0; i < str.length; i++) {
			ch = str.charCodeAt(i);
			st = [];
			do {
				st.push(ch & 0xFF);
				ch = ch >> 8;
			} while (ch);
			re = re.concat(st.reverse());
		}
		return re;
	}

	/**
	 * 是否完全包含另一个数组
	 * @param {Object} aa 小数组
	 * @param {Object} bb 大数组
	 */
	function isInclude(aa, bb) {
		return aa.every((item) => {
			return bb.some((sub) => {
				return sub === item;
			})
		})
	}

	// 数组是否重复
	function isRepeat(aArr, bArr) {
		for (let i = 0; i < aArr.length; i++) {
			if (isInclude(bArr, aArr[i])) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 获取首个0后一位（EPC开头）到密码0前一位（EPC结束）的下标
	 * @param {Object} arr 0的下标数组
	 */
	function getDataFristToEndIndex(arr) {
		let len = arr.length;
		if (len <= 1) {
			return -1;
		}
		var end = 0;
		// 首个0的位置+1（EPC开头）
		let first = arr[0];
		let index = 0;
		for (let i = 0; i < len; i++) {
			if (i + 1 < 0) {
				if (arr[i + 1] - arr[i] === 1) {
					end = arr[i + 1];
					break;
				}
			}
		}
		return (end === 0) ? -1 : [first + 1, end - 1];
	}

	// bytes是否大于127或小于-128
	function ifB127SF128(arr) {
		for (let i = 0; i < arr.length; i++) {
			if (arr[i] > 127) {
				arr[i] = arr[i] - 256;
			}else if(arr[i] < (-128)){
				arr[i] = arr[i]+256;
			}else{
				arr[i] = arr[i];
			}
		}
		return arr;
	}

	// 计算天线值
	function checkSum(arr, zero, len) {
		let btSum = 0;
		for (let nloop = zero; nloop < zero + len; nloop++) {
			btSum += parseInt(arr[nloop]);
			console.log(btSum + "====" + parseInt(arr[nloop]))
		}
		let result = (~btSum) + 1;
		if (result > 127) {
			return (result - 256);
		} else if (result < (-128)) {
			return (result + 256);
		} else {
			return result;
		}
	}

	// 写入标签数据（格式处理）
	function setLable(str) {
		let arr = new Array();
		let len = str.length / 2;
		// 将数据长度写到首位
		arr.push(parseInt(len));
		// 将字符串中的S替换成A
		str = str.replace('S', 'A');
		if ((len % 2) === 0) {
			// 偶数
			let index = 0;
			do {
				len--;
				let c = str.substr(index, 2);
				let byt = HexString2Bytes(c);
				index += 2;
				if (byt > 127) {
					arr.push(parseInt(byt-256));
				} else if (byt < (-128)) {
					arr.push(parseInt(byt+256));
				} else {
					arr.push(parseInt(byt));
				}
			} while (len > 0)
		} else {
			// 偶数
			let index = 0;
			do {
				len--;
				let c = str.substr(index, 2);
				let byt = HexString2Bytes(c);
				index += 2;
				if (byt > 127) {
				arr.push(parseInt(byt-256));
				} else if (byt < (-128)) {
					arr.push(parseInt(byt+256));
				} else {
					arr.push(parseInt(byt));
				}
			} while (len > 0)
		}
		return arr;
	}

	// let bb = setLable("1200069S");
	// console.log(bb)
	// let hex = bytesToHexArr(bb);
	// console.log(hex)
	// console.log(hex2DataString(hex))
	//-96 15 1 -126 0 0 0 0 1 2 3 5 18 0 6 -102 17 |A0 0F 01 82 00 00 00 00 01 02 03 05 12 00 06 9A 11

	// let arr = [-96,17,-1,-123,0,12,4,18,0,6,-103,19,-35,-70,0,0,0,0];
	// console.log(checkSum(arr, 0, arr.length));

	// let mm = [-96,15,1,-126,0,0,0,0,1,2,3,4,18,0,6,-103]; // 19
	// console.log(checkSum(mm,0,mm.length));

	// let arr = [160,19,1,137,212,52,0,23,32,86,32,9,18,0,0,0,0,0,0,75,168]
	// let zeroIndex = getArrayIndex(arr,0);
	// console.log(zeroIndex); 
	// console.log(getDataToFirstPasswordIndex(zeroIndex))

	document.addEventListener("plusready", function() {
		var vm = new Vue({
			"el": "#app",
			data: function() {
				return {
					msg: '刷新',
					isSearch: false, // 是否开始扫描蓝牙
					Pairedlist: [], // 已配对的蓝牙列表
					Unpairedlist: [], // 未匹配的蓝牙列表
					blue: null, // 当前组件全局蓝牙类
					dataList: [{
						hex: null,
						arr: null
					}], //扫描标签列表
					firmwareId: null, // 固件版本
					temperature: null, // 工作温度
					read_lableId: null, // 读取单个标签
					select_lableId: null, // 选取单个标签
					set_lableId: null, // 写入的标签
					is_select: false
				}
			},
			methods: {
				// 开始获取版本
				open_read_firmware: function() {
					if (bleSocket !== null && timer === null) {
						bleSocket.close();
						var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
							BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
							UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
							// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
							uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
							BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
							device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
						BAdapter.cancelDiscovery();
						plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
						var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
						bleSocket = bluetoothSocket;
						plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
						console.log(bleSocket.isConnected())
						if (!bleSocket.isConnected()) {
							bleSocket.connect();
							console.log("重新连接成功")
						} else {
							bleSocket.close();
							bleSocket.connect();
						}
						let obj = document.getElementById("read_firmware");
						this.firmwareId = null;
						clearInterval(timer);
						timer === null;
						if (timer === null && this.firmwareId === null) {
							timer = setInterval(this.read_firmware, 100);
						}
					} else {
						if (bleSocket === null) {
							console.log("设备没有连接！");
							return;
						} else {
							console.log("不是第一次连接")
							bleSocket.close();
							var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
								BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
								UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
								// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
								device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
							BAdapter.cancelDiscovery();
							plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
							var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
							bleSocket = bluetoothSocket;
							plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
							console.log(bleSocket.isConnected())
							if (!bleSocket.isConnected()) {
								bleSocket.connect();
							} else {
								bleSocket.close();
								bleSocket.connect();
							}
							let obj = document.getElementById("read_firmware");
							this.firmwareId = null;
							clearInterval(timer);
							timer === null;
							if (timer === null && this.firmwareId === null) {
								timer = setInterval(this.read_firmware, 100);
							}
						}
					}
				},
				//获取固件版本
				read_firmware: function() {
					let invoke = plus.android.invoke;
					var os = invoke(bleSocket, "getOutputStream");
					console.log("获取固件版本:");
					let dataArr = new Array();
					while (1) {
						plus.android.importClass(bleSocket);
						let bytes = [-96, 3, 1, 114, -22];
						plus.android.importClass(os);
						var oi = invoke(bleSocket, "getInputStream");
						plus.android.importClass(oi);
						this.firmwareId = null;
						os.write(bytes);
						let data = invoke(oi, "read");
						dataArr.push(data);
						if (data === 160 && dataArr.length > 1) {
							for (var i = 0; i < dataArr.length; i++) {
								if (dataArr[i] === 160) {
									dataArr.splice(i, 1);
									break;
								}
							}
							dataArr.unshift(160);
							// 获取版本个位
							console.log(dataArr)
							// 获取主版本号
							let bit = dataArr[4];
							console.log(bit)
							// 后去次版本号
							let dec = dataArr[5] / 10;
							// 获取版本小数
							this.firmwareId = Math.round(bit) + dec
							console.log(this.firmwareId)
							if (this.firmwareId !== null) {
								clearInterval(timer);
								timer = null;
								return;
							}
							dataArr = [];
							return;
						}
					}
				},
				// 开始获取温度
				open_read_temperature: function() {
					if (bleSocket !== null && timer === null) {
						bleSocket.close();
						var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
							BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
							UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
							// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
							uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
							BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
							device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
						BAdapter.cancelDiscovery();
						plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
						var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
						bleSocket = bluetoothSocket;
						plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
						console.log(bleSocket.isConnected())
						if (!bleSocket.isConnected()) {
							bleSocket.connect();
							console.log("重新连接成功")
						} else {
							bleSocket.close();
							bleSocket.connect();
						}
						this.temperature = null;
						clearInterval(timer);
						timer === null;
						if (timer === null && this.temperature === null) {
							timer = setInterval(this.read_temperature, 100);
						}
					} else {
						if (bleSocket === null) {
							console.log("设备没有连接！");
							return;
						} else {
							bleSocket.close();
							var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
								BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
								UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
								// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
								device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
							BAdapter.cancelDiscovery();
							plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
							var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
							bleSocket = bluetoothSocket;
							plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
							console.log(bleSocket.isConnected())
							if (!bleSocket.isConnected()) {
								bleSocket.connect();
							} else {
								bleSocket.close();
								bleSocket.connect();
							}
							this.temperature = null;
							clearInterval(timer);
							timer === null;
							if (timer === null && this.temperature === null) {
								timer = setInterval(this.read_temperature, 100);
							}
						}
					}
				},
				//获取设备工作温度
				read_temperature: function() {
					try {
						let invoke = plus.android.invoke;
						var os = invoke(bleSocket, "getOutputStream");
						console.log("获取设备工作温度:");
						let dataArr = new Array();
						while (1) {
							plus.android.importClass(bleSocket);
							let bytes = [-96, 3, -1, 123, -29]; // 温度上位机代码
							plus.android.importClass(os);
							var oi = invoke(bleSocket, "getInputStream");
							plus.android.importClass(oi);
							this.temperature = null;
							os.write(bytes);
							// os.flush();
							let data = invoke(oi, "read");
							dataArr.push(data);
							if (data === 160 && dataArr.length > 1) {
								for (var i = 0; i < dataArr.length; i++) {
									if (dataArr[i] === 160) {
										dataArr.splice(i, 1);
										break;
									}
								}
								dataArr.unshift(160);
								//获取是否为零上温度(0为零下，1为零上)
								let positive = dataArr[4];
								// 获取温度数
								console.log(dataArr)
								let bit = dataArr[5];
								if (positive !== 1) {
									bit = 0 - bit;
								}
								this.temperature = Math.round(bit) + "℃";
								if (this.temperature !== null) {
									clearInterval(timer);
									timer = null;
									return;
								}
								dataArr = [];
								return;
							}
						}
					} catch (err) {
						console.log(err + "获取设备温度失败！");
					}
				},
				// 开始读取标签
				open_read_lable: function() {
					if (this.is_select === false) {
						console.log("未选取标签，请选取标签！")
						return;
					}
					if (bleSocket !== null && timer === null) {
						bleSocket.close();
						var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
							BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
							UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
							// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
							uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
							BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
							device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
						BAdapter.cancelDiscovery();
						plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
						var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
						bleSocket = bluetoothSocket;
						plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
						if (!bleSocket.isConnected()) {
							bleSocket.connect();
						} else {
							bleSocket.close();
							bleSocket.connect();
						}
						this.read_lableId = null;
						clearInterval(timer);
						timer = null;
						if (timer === null && this.read_lableId === null) {
							timer = setInterval(this.read_lable, 100);
						}
					} else {
						if (bleSocket === null) {
							console.log("设备没有连接！");
							return;
						} else {
							bleSocket.close();
							var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
								BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
								UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
								// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
								device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
							BAdapter.cancelDiscovery();
							plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
							var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
							bleSocket = bluetoothSocket;
							plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
							if (!bleSocket.isConnected()) {
								bleSocket.connect();
							} else {
								bleSocket.close();
								bleSocket.connect();
							}
							this.read_lableId = null;
							clearInterval(timer);
							timer = null;
							if (timer === null && this.read_lableId === null) {
								timer = setInterval(this.read_lable, 100);
							}
						}
					}
				},
				// 读取标签
				read_lable: function() {
					try {
						// 注册输入输出流
						let invoke = plus.android.invoke;
						btOutStream = invoke(bleSocket, "getOutputStream");
						plus.android.importClass(bleSocket);
						let bytes = [-96, 10, 1, -127, 1, 2, 6, 0, 0, 0, 0];
						let btCheck = checkSum(bytes, 0, bytes.length);
						bytes.push(btCheck);
						console.log("读取标签：" + bytes);
						plus.android.importClass(btOutStream);
						let dataArr = new Array();
						// 返回标签数据
						try {
							btInStream = invoke(bleSocket, "getInputStream");
							plus.android.importClass(btInStream);
							while (1) {
								btOutStream.write(bytes);
								// btOutStream.flush();
								let data = invoke(btInStream, "read");
								if (data === 160 && dataArr.length > 1) {
									this.read_lableId = bytesToHexArr(dataArr);
									if (this.read_lableId !== null) {
										this.is_select = false;
										dataArr.length = [];
										clearInterval(timer);
										timer = null;
										return;
									}
								} else {
									dataArr.push(data);
								}
							}
						} catch (err) {
							console.log(err);
						}
					} catch (err) {
						console.log("读取标签失败！")
					}
				},
				// 开始选中标签
				open_select_lable: function(arr) {
					firstSelect++;
					if (this.is_select === true) {
						console.log("已选取标签，请读取标签数据或编辑标签数据！")
						return;
					}
					arr = ifB127SF128(arr);
					console.log(arr)
					console.log(this.select_lableId)
					if (timer !== null) {
						clearInterval(timer);
						timer = null;
						this.open_select_lable();
					} else {
						if (bleSocket !== null && timer === null) {
							bleSocket.close();
							var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
								BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
								UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
								// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
								device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
							BAdapter.cancelDiscovery();
							plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
							var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
							bleSocket = bluetoothSocket;
							plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
							if (!bleSocket.isConnected()) {
								bleSocket.connect();
							} else {
								bleSocket.close();
								bleSocket.connect();
							}
							this.select_lableId = null;
							clearInterval(timer);
							timer = null;
							if (timer === null && this.select_lableId === null) {
								timer = setInterval(this.select_lable(arr), 100);
							}
						} else {
							if (bleSocket === null) {
								console.log("设备没有连接！");
								return;
							} else {
								bleSocket.close();
								var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
									BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
									UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
									// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
									uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
									BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
									device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
								BAdapter.cancelDiscovery();
								plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
								var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
								bleSocket = bluetoothSocket;
								plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
								if (!bleSocket.isConnected()) {
									bleSocket.connect();
								} else {
									bleSocket.close();
									bleSocket.connect();
								}
								this.select_lableId = null;
								clearInterval(timer);
								timer = null;
								if (timer === null && this.select_lableId === null) {
									timer = setInterval(this.select_lable(arr), 100);
								}
							}
						}
					}
				},
				// 选取标签
				select_lable: function(arr) {
					try {
						let invoke = plus.android.invoke;
						var os = invoke(bleSocket, "getOutputStream");
						console.log("开始选中标签:" + arr);
						let dataArr = new Array();
						while (1) {
							plus.android.importClass(bleSocket);
							let signFirst = [-96, 17, -1, -123, 0, 12]; // 首次选取标签
							let signSecond = [-96, 17, 1, -123, 0, 12]; // 不是首次选取标签
							// let lableId = [23, 32, 86, 32, 9, 18 , 0, 0, 0, 0, 0, 0];
							// 获取标签上位机代码
							let bytes = new Array();
							if (firstSelect === 0) {
								for (let i = 0; i < signFirst.length; i++) {
									bytes.push(signFirst[i]);
								}
							} else {
								for (let k = 0; k < signSecond.length; k++) {
									bytes.push(signSecond[k]);
								}
							}
							for (let j = 0; j < arr.length; j++) {
								bytes.push(arr[j]);
							}
							let btCheck = checkSum(bytes, 0, bytes.length);
							bytes.push(btCheck);
							console.log(bytes)
							// console.log(bytes)
							// console.log(bytesToHexArr(bytes));
							plus.android.importClass(os);
							var oi = invoke(bleSocket, "getInputStream");
							plus.android.importClass(oi);
							this.select_lableId = null;
							os.write(bytes);
							// os.flush();
							let data = invoke(oi, "read");
							// console.log(data)
							if (data === 160 && dataArr.length > 1) {
								// console.log(dataArr)
								// console.log(bytesToHexArr(dataArr))

								this.select_lableId = dataArr;
								if (this.select_lableId !== null) {
									this.is_select = true;
									console.log("选取标签成功 ：" + arr)
									dataArr = [];
									clearInterval(timer);
									timer = null;
									return;
								}
							} else {
								dataArr.push(data);
							}
						}
					} catch (err) {
						console.log(err + "选取标签失败！");
					}
				},
				// 开始写入标签
				open_set_lable: function(arr) {
					if (timer !== null) {
						clearInterval(timer);
						timer = null;
						this.open_set_lable();
					} else {
						if (bleSocket !== null && timer === null) {
							bleSocket.close();
							var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
								BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
								UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
								// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
								device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
							BAdapter.cancelDiscovery();
							plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
							var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
							bleSocket = bluetoothSocket;
							plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
							if (!bleSocket.isConnected()) {
								bleSocket.connect();
							} else {
								bleSocket.close();
								bleSocket.connect();
							}
							this.set_lableId = null;
							clearInterval(timer);
							timer = null;
							if (timer === null && this.set_lableId === null) {
								timer = setInterval(this.set_lable(arr), 100);
							}
						} else {
							if (bleSocket === null) {
								console.log("设备没有连接！");
								return;
							} else {
								bleSocket.close();
								var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
									BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
									UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
									// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
									uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
									BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
									device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
								BAdapter.cancelDiscovery();
								plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
								var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
								bleSocket = bluetoothSocket;
								plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
								if (!bleSocket.isConnected()) {
									bleSocket.connect();
								} else {
									bleSocket.close();
									bleSocket.connect();
								}
								this.set_lableId = null;
								clearInterval(timer);
								timer = null;
								if (timer === null && this.select_lableId === null) {
									timer = setInterval(this.set_lable(arr), 100);
								}
							}
						}
					}
				},
				// 写入标签
				set_lable: function(str) {
					try {
						let invoke = plus.android.invoke;
						var os = invoke(bleSocket, "getOutputStream");
						let dataArr = new Array();
						str = "12007304";
						console.log("写入标签:" + str);
						// arr = ifB127SF128(arr);
						while (1) {
							plus.android.importClass(bleSocket);
							let sign = [-96, 15, 1, -126, 0, 0, 0, 0, 1, 2, 3];
							// 将写入的数据进行处理 // -96,15,1,-126,0,0,0,0,1,2,3,4,18,0,115,4,59
							                      // -96 15 1 -126 0 0 0 0 1 2 3 4 18 0 115 4 59
							let arr = setLable(str);
							for(let dd = 0;dd<arr.length;dd++){
								console.log(typeof arr[dd]);
							}
							// 设置上位机字节流
							let bytes = new Array();
							for (let i = 0; i < sign.length; i++) {
								bytes.push(sign[i]);
							}
							for (let j = 0; j < arr.length; j++) {
								bytes.push(arr[j]);
							}
							
							// 计算天线值
							let btCheck = checkSum(bytes,0,bytes.length);
							bytes.push(btCheck);
							console.log(bytes);
							plus.android.importClass(os);
							var oi = invoke(bleSocket, "getInputStream");
							plus.android.importClass(oi);
							this.select_lableId = null;
							os.write(bytes);
							// os.flush();
							let data = invoke(oi, "read");
							// console.log(data)
							if (data === 160 && dataArr.length > 1) {
								this.set_lableId = dataArr;
								if (this.set_lableId !== null) {
									console.log("写入标签成功 ：" + str)
									this.is_select = false;
									dataArr = [];
									clearInterval(timer);
									timer = null;
									return;
								}
							} else {
								dataArr.push(data);
							}
						}
					} catch (err) {
						console.log(err + "写入标签失败！");
					}
				},
				// 复位读写器
				reset: function() {
					try {
						if (bleSocket === null) {
							console.log("复位失败！设备未连接！");
							return;
						}
						let invoke = plus.android.invoke;
						btOutStream = invoke(bleSocket, "getOutputStream");
						plus.android.importClass(bleSocket);
						// let head = -96; //0xA0
						// let len = 3; //0x03
						// let address = -1; //0xFF
						// let cmd = 112; //0x70
						// let check = -18; //0xEE
						let bytes = [-96, 3, -1, 112,-18];
						console.log("复位:" + bytes);
						plus.android.importClass(btOutStream);
						btOutStream.write(bytes);
						btOutStream.flush();
						console.log("复位成功！");
					} catch (err) {
						console.log(err + "复位失败！");
					}
				},
				open: function() {
					let obj = document.getElementById("scanButton");
					if (timer === null) {
						if (bleSocket !== null && timer === null) {
							bleSocket.close();
							var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
								BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
								UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
								// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
								device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
							BAdapter.cancelDiscovery();
							plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
							var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
							bleSocket = bluetoothSocket;
							plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
							if (!bleSocket.isConnected()) {
								bleSocket.connect();
							} else {
								bleSocket.close();
								bleSocket.connect();
							}
							timer = setInterval(this.getMessage, 200);
							obj.innerHTML = "取消盘点";
							console.log("开始扫描...")
						} else {
							bleSocket.close();
							var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
								BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
								UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
								// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
								BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
								device = BAdapter.getRemoteDevice(connectId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
							BAdapter.cancelDiscovery();
							plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
							var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
							bleSocket = bluetoothSocket;
							plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
							if (!bleSocket.isConnected()) {
								bleSocket.connect();
							} else {
								bleSocket.close();
								bleSocket.connect();
								console.log("重新连接成功！")
							}
							timer = setInterval(this.getMessage, 200);
							obj.innerHTML = "取消盘点";
							console.log("开始扫描...")
						}
					} else {
						clearInterval(timer);
						timer = null;
						obj.innerHTML = "开始盘点"
						console.log("取消盘点...")
					}
				},
				// 扫描标签
				getMessage: function() {
					// 开始盘点
					console.log("扫描中。。。")
					try {
						plus.android.importClass(bleSocket);
						let invoke = plus.android.invoke;
						let bytes = [-96, 4, -1, -119, 1];
						// 设置天线
						let btCheck = checkSum(bytes, 0, bytes.length);
						bytes.push(btCheck);

						btOutStream = invoke(bleSocket, "getOutputStream");
						plus.android.importClass(btOutStream);
						btOutStream.write(bytes);
						// 开始接收标签信息
						let dataArr = new Array();
						try {
							btInStream = invoke(bleSocket, "getInputStream");
							plus.android.importClass(btInStream);
							while (1) {
								let data = invoke(btInStream, "read");
								if (dataArr.length === 0) {
									dataArr.push(data);
								} else if (data === 160 && dataArr.length > 0) {
									if (!isInclude([160], dataArr)) {
										dataArr.unshift(data);
									}
									console.log(dataArr);
									let errCode = [160, 10, 1, 137, 0, 0];
									let err2Code = [160, 86, 32, 3, 24, 0];
									if (!isInclude(errCode, dataArr) && !isInclude(err2Code, dataArr)) {
										// 获取首个0下标
										let zeroIndex = getArrayIndex(dataArr, 0)
										if (zeroIndex.length < 1 && zeroIndex === -1) {
											break;
										}
										dataArr = dataArr.splice(zeroIndex[0] + 1, (dataArr.length - zeroIndex[0]) - 3);
										console.log(dataArr);
										if (this.dataList != null && this.dataList.length > 0) {
											let obj = {
												hex: bytesToHexArr(dataArr),
												arr: dataArr
											}
											let key = 0;
											for (let i = 0; i < this.dataList.length; i++) {
												if (isInclude(obj.arr, this.dataList[i].arr)) {
													key = 1;
													break;
												}
											}
											if (key === 0) {
												if (dataArr.length > 4) {
													console.log(obj.arr)
													let hexArr = bytesToHexArr(obj.arr);
													console.log(hexArr);
													// let str = hexArr2String(hexArr);
													let str = hex2String(hexArr);
													console.log(str);
													this.dataList.push(obj);
													console.log(key + "添加了：" + obj.arr)
												}
											}
										} else {
											if (dataArr.length > 4 && this.dataList.length === 0) {
												let obj = {
													hex: bytesToHexArr(dataArr),
													arr: dataArr
												}
												console.log(obj.arr);
												let hexArr = bytesToHexArr(obj.arr);
												console.log(hexArr);
												let str = hex2String(hexArr);
												console.log(str);
												this.dataList.push(obj);
											}
										}
									}
									dataArr = [];
									break;
								} else {
									dataArr.push(data);
								}
							}
						} catch (err) {
							console.log(err);
						}
					} catch (e) {
						console.log(e);
					}
				},
				// 搜索蓝牙设备
				startBlue: function() {
					var self = this;
					self.dataList = [];
					if (!self.blue.CheckBluetoothState()) { // 判断是否开启蓝牙
						self.blue.StartBluetooth();
						return;
					}
					self.Pairedlist = [];
					self.Unpairedlist = [];
					self.isSearch = true;
					mui('.mui-btn').button('loading');
					self.blue.StartSeatch(function(obj) {
						// console.log(obj.bleName)
						// console.log(obj.isPaired)
						if (obj) {
							if (obj.bleName) {
								if (obj.isPaired) {
									self.Pairedlist.push(obj);
								} else {
									self.Unpairedlist.push(obj);
								}
							}
						}
					}, function() {
						self.msg = '重新刷新！';
						mui('.mui-btn').button('reset');
						self.isSearch = false;
					});
				},
				// 进行配对
				Bluepairing: function(index) {
					if (!this.Unpairedlist[index]) {
						mui.toast('设备不存在');
						return;
					}
					var self = this,
						BleDevice = self.Unpairedlist[index].BleDevice,
						bleId = self.Unpairedlist[index].bleId;
					mui('.mui-btn').button('loading');
					self.blue.Bluepairing(BleDevice, bleId, function(msg) {
						mui.toast(msg.errmsg);
						self.Pairedlist.push(self.Unpairedlist[index]); // 已配对设备新增元素
						self.Unpairedlist.splice(index, 1); // 未配对设备删除元素
						self.msg = '配对结束，重新搜索！';
						mui('.mui-btn').button('reset');
					}, function(msg) {
						mui.toast(msg.errmsg);
						self.msg = '配对结束，重新搜索！';
						mui('.mui-btn').button('reset');
					});
				},
				// 连接设备
				ConnectDevice: function(index) {
					var self = this;
					mui.plusReady(function() {
						var bleId = self.Pairedlist[index].bleId;
						console.log(bleId);
						connectId = bleId;
						var plusMain = plus.android.runtimeMainActivity(), // Android原生应用的主Activity对象
							BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), // 引入蓝牙设备操作类
							UUID = plus.android.importClass("java.util.UUID"), // 引入生成UUID类
							// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
							uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // 生成UUIID
							BAdapter = BluetoothAdapter.getDefaultAdapter(), // 获得蓝牙适配器实例
							device = BAdapter.getRemoteDevice(bleId); // 以给定的MAC地址去创建一个 BluetoothDevice 类实例(代表远程蓝牙实例)。
						connectDevice = device;
						BAdapter.cancelDiscovery();
						plus.android.importClass(device); // 引入 BluetoothDevice 类实例 方便 . 操作
						var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); // 创建连接实例
						bleSocket = bluetoothSocket;
						plus.android.importClass(bluetoothSocket); // 引入 实例 方便 . 操作
						// 判断是否连接 没有连接则连接
						try {
							if (!bluetoothSocket.isConnected()) {
								bluetoothSocket.connect();
								mui.toast('连接成功！');
							}
						} catch (err) {
							bluetoothSocket.close();
							mui.toast('断开连接！');
						}
					});
				},
				SearchBluetooth: function() {
					/*plus变量定义*/
					var main, BluetoothAdapter, BAdapter, IntentFilter, BluetoothDevice, receiver;
					/*其他定义*/
					var isSearchDevices = false, //是否处于搜索状态
						debug = false; //调试模式
					main = plus.android.runtimeMainActivity(),
						BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"),
						IntentFilter = plus.android.importClass('android.content.IntentFilter'),
						BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice"),
						BAdapter = new BluetoothAdapter.getDefaultAdapter();
					return {
						// 检查蓝牙是否开启
						CheckBluetoothState: function() {
							return BAdapter.isEnabled();
						},
						// 开启蓝牙
						StartBluetooth: function() {
							var self = this;
							if (!BAdapter.isEnabled()) { // isEnabled判断蓝牙状态
								BAdapter.enable(); // 请求开启蓝牙
							}
						},
						// 开始搜索设备
						StartSeatch: function(CallBack, errcallback) {
							try {
								var self = this;
								isSearchDevices = true;
								var filter = new IntentFilter(),
									bdevice = new BluetoothDevice();
								BAdapter.startDiscovery(); //开启搜索
								receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
									onReceive: onReceiveFn
								});
								filter.addAction(bdevice.ACTION_FOUND);
								filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
								filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
								filter.addAction(BAdapter.ACTION_STATE_CHANGED);
								main.registerReceiver(receiver, filter); //注册监听事件
								//监听回调函数  回调函数会在搜索期间 持续调用
								console.log("开始扫描...");

								function onReceiveFn(context, intent) {
									plus.android.importClass(intent); //通过intent实例引入intent类，方便以后的‘.’操作
									//开始搜索改变状态
									intent.getAction() === "android.bluetooth.device.action.FOUND" && (isSearchDevices = true);
									//判断是否搜索结束
									if (intent.getAction() === 'android.bluetooth.adapter.action.DISCOVERY_FINISHED') {
										main.unregisterReceiver(receiver); //取消监听
										isSearchDevices = false;
										errcallback();
										return;
									}
									var BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE), // 设备对象
										bleName = BleDevice.getName(), //设备名称
										bleId = BleDevice.getAddress(); //设备mac地址
									if (!bleName || !bleId) {
										CallBack(false);
									}
									//判断是否配对
									if (BleDevice.getBondState() === bdevice.BOND_BONDED) { // 已配对的蓝牙设备
										CallBack({
											BleDevice: BleDevice,
											bleName: bleName, // 设备名称
											bleId: bleId, // 设备id
											isPaired: true
										});
									} else { // 未配对的蓝牙设备
										CallBack({
											BleDevice: BleDevice,
											bleName: bleName, // 设备名称
											bleId: bleId, // 设备id
											isPaired: false
										});
									}
								}
							} catch (err) {
								errcallback();
							}
						},
						// 配对蓝牙设备
						Bluepairing: function(BleDevice, bleId, CallBack, ErrCallBack) {
							try {
								var self = this,
									bdevice = new BluetoothDevice(), // new java android.bluetooth.BluetoothDevice对象
									BleDeviceItem = BleDevice; // 赋值设备
								if (BleDeviceItem.getAddress() === bleId) {
									BleDeviceItem.createBond(); // 设备进行配对
									var timeout = setInterval(function() { // 创建定时器轮询配对结果
										if (BleDeviceItem.getBondState() === bdevice.BOND_BONDED) { // 配对成功
											window.clearInterval(timeout);
											CallBack({
												status: true,
												errmsg: '配对成功'
											});
										} else if (BleDeviceItem.getBondState() === bdevice.BOND_NONE) { // 配对失败
											window.clearInterval(timeout);
											ErrCallBack({
												status: false,
												errmsg: '配对失败,请尝试重新配对'
											});
										}
									}, 1000);
								} else {
									ErrCallBack({
										status: false,
										errmsg: '设备有误'
									});
								}
							} catch (err) {
								ErrCallBack({
									status: false,
									errmsg: '异常错误'
								});
							}
						}
					}
				}
			},
			// 初始化
			mounted: function() {
				// 初始化创建对象
				var self = this;
				mui.plusReady(function() {
					self.blue = new self.SearchBluetooth();
				});
			}
		})
	})
</script>
